package ThreadTest;

import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-06-11
 * Time: 21:35
 */
public class Deom1 {
    public static int sum1 = 0;
    public static int sum2 = 0;
    public static int sum = 0;
    public static void main(String[] args) throws InterruptedException {
        Object locker = new Object();
        //获取当时时间的毫秒数
        long currentTimeMillis = System.currentTimeMillis();
        // 使用当前时间的毫秒数作为种子初始化Random对象
        Random random = new Random(currentTimeMillis);
        //创建一个10000大小的数组
        int[] array = new int[1_0000];
        //将生成1-100的随机数放入数组array中
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(100) + 1;
        }
        //创建t1线程
        Thread t1 = new Thread(() -> {
            synchronized(locker) {
                for (int i = 0; i < array.length; i += 2) {
                    sum1 += array[i];
                }
            }
        });
        //创建t2线程
        Thread t2 = new Thread(() -> {
            synchronized(locker) {
                for (int i = 1; i < array.length; i += 2) {
                    sum2 += array[i];
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        sum = sum1 + sum2;
        //记录程序结束的时间
        long endTime = System.currentTimeMillis();
        //计算整个程序的时间
        long executionTime = endTime - currentTimeMillis;
        System.out.println("sum = " + sum +"     "+"executionTime = " + executionTime );
    }
}
